<template>
  <div class="roles-container">
    <!-- 头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- roles内容区域 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleVisible">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="rolesList" stripe style="width: 100%" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="[
                'bottom-border',
                index === 0 ? 'top-border' : '',
                'ycenter'
              ]"
            >
              <!-- 一级权限 -->
              <el-col :span="6"
                ><el-tag :class="'margin-left'">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i
              ></el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="18">
                <el-row
                  :class="[index1 === 0 ? '' : 'top-border', 'ycenter']"
                  v-for="(item1, index1) in item.children"
                  :key="item1.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="9">
                    <el-tag type="success" :class="'margin-left'">{{
                      item1.authName
                    }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="15">
                    <el-tag
                      closable
                      @close="removeTag(scope.row, item2.id)"
                      :class="'margin-left'"
                      type="warning"
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="updateRolesVisible(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteVisity(scope.row.id)"
              >删除</el-button
            >
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="rightVisity(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addFormVisible"
      @close="closeReset"
    >
      <el-form :model="addform" :rules="addRolesrules" ref="addFormRef">
        <el-form-item label="角色名称" label-width="80px" prop="roleName">
          <el-input v-model="addform.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="80px" prop="roleDesc">
          <el-input v-model="addform.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewRole()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑用户" :visible.sync="updateFormVisible">
      <el-form :model="updateForm" ref="updatesForm" :rules="updateRolesrules">
        <el-form-item label="角色名称" label-width="80px" prop="roleName">
          <el-input v-model="updateForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="80px">
          <el-input v-model="updateForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightdialogVisible"
      width="30%"
      @close="resetdefKeys"
    >
      <el-tree :data="rightList" :props="rightProps" ref="treeRef" show-checkbox default-expand-all node-key="id" :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="givePermissions"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入rolesAPI接口
import { rolesAPI } from '@/api/rolesAPI.js'
// 导入addRolesAPI接口
import { addRolesAPI } from '@/api/addRolesAPI.js'
// 导入updateAPI接口
import { updateRoleAPI } from '@/api/updateRoleAPI.js'
// 导入updateGetRoleAPI接口
import { updateGetRoleAPI } from '@/api/updateGetRoleAPI.js'
// 导入deleteRolesAPI接口
import { deleteRolesAPI } from '@/api/deleteRolesAPI.js'
// 导入removePermissionsAPI接口
import { removePermissionsAPI } from '@/api/removePermissionsAPI.js'
// 导入getRightListAPI接口
import { getRightListAPI } from '@/api/getRightsListAPI.js'
// 导入givePermissionsAPI接口
import { givePermissionsAPI } from '@/api/givePermissionsAPI.js'
export default {
  name: 'Roles',
  data() {
    return {
      // 存储后台返回的角色列表
      rolesList: [],
      // 添加角色表单的显示状态
      addFormVisible: false,
      // 编辑角色表单显示状态
      updateFormVisible: false,
      // 添加角色列表信息
      addform: {
        roleName: '',
        roleDesc: ''
      },
      // 添加用户预验证
      addRolesrules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      // 获取角色名称和角色描述
      updateForm: {},
      // 添加用户预验证
      updateRolesrules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      // 删除角色对话框显示状态
      deleteVisible: false,
      // 角色权限分配对话框显示状态
      rightdialogVisible: false,
      // 权限列表
      rightList: [],
      // 规定子选项以及子选项的名称
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      // 角色已有权限
      defKeys: [],
      // 角色的id
      roleId: ''
    }
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data: res } = await rolesAPI()
      // console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    // 关闭对话框重置内容
    closeReset() {
      this.$refs.addFormRef.resetFields()
    },
    // 显示添加角色对话框
    addRoleVisible() {
      // 添加用户对话框显示
      this.addFormVisible = true
    },
    // 添加并获取角色
    addNewRole() {
      // 如果表单与验证通过则发送请求
      this.$refs.addFormRef.validate(async(valid) => {
        if (!valid) return
        // 获取修改角色列表数据
        const { data: res } = await addRolesAPI(this.addform)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.getRolesList()
        this.addFormVisible = false
        this.$refs.addFormRef.resetFields()
      })
    },
    // 获取最新的角色数据
    // 显示编辑角色表单
    async updateRolesVisible(id) {
      this.updateFormVisible = true
      // console.log(id)
      const { data: res } = await updateGetRoleAPI(id)
      // console.log(res)
      this.updateForm = res.data
    },
    // 修改角色
    updateRoles() {
      this.$refs.updatesForm.validate(async(valid) => {
        if (!valid) return
        const { data: res } = await updateRoleAPI(
          this.updateForm.roleId,
          this.updateForm.roleName,
          this.updateForm.roleDesc
        )
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改角色失败')
        this.$message.success('修改角色成功')
        this.updateFormVisible = false
        this.getRolesList()
      })
    },
    // 删除角色
    async deleteVisity(id) {
      this.deleteVisible = true
      console.log(id)
      const result = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (result !== 'confirm') return this.$message.info('删除已取消')
      const { data: res } = await deleteRolesAPI(id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
    },
    async removeTag(role, rightId) {
      // console.log(role, rightId)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('删除已取消')
      }
      const { data: res } = await removePermissionsAPI(role.id, rightId)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      role.children = res.data
    },
    // 控制角色分配权限对话框显示
    async rightVisity(right) {
      this.roleId = right.id
      // console.log(this.roleId)
      const { data: res } = await getRightListAPI()
      if (res.meta.status !== 200) return
      // console.log(res)
      this.rightList = res.data
      // console.log(right)
      this.getTree(right, this.defKeys)
      this.rightdialogVisible = true
    },
    // 获取所有三级权限的id
    getTree(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getTree(item, arr)
      })
    },
    // 当分配角色对话框关闭将defkeys重置为空数组，防止不同角色的权限叠加在一起
    resetdefKeys() {
      this.defKeys = []
    },
    // 给角色分配权限
    async givePermissions() {
      const permissionsArr = [
        ...this.$refs.treeRef.getHalfCheckedNodes(),
        ...this.$refs.treeRef.getCheckedKeys()
      ]
      console.log(permissionsArr)
      const arrStr = permissionsArr.join(',')
      // console.log(arrStr)
      const { data: res } = await givePermissionsAPI(this.roleId, arrStr)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新权限失败')
      this.$message.success('更新角色权限成功')
      this.getRolesList()
      this.rightdialogVisible = false
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}

.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 10px 0;
}
.bottom-border {
  border-bottom: 1px solid #eee;
}
.top-border {
  border-top: 1px solid #eee;
}
.margin-left {
  margin-left: 15px;
}
.ycenter {
  display: flex;
  align-items: center;
}
</style>
